< previous page page_361 next page >

Page 361
Polymorphism. Although many objects can have methods bearing the same name, the method can perform differently for each of the objects. Through polymorphism, the program runs the method appropriate for the current object. For example, the + operator can be used with both strings and integers. Even though the same symbol is used for both data types, Visual Basic knows to perform different operations.
An important consequence of an OOP approach is reusable code. Part of what makes an object reusable is its interface, or the methods and properties the object uses to communicate with the outside world. If you build objects with well-defined interfaces, it is easy to change the object internally or even add new interfaces without affecting programs that use the object.
Classes in Visual Basic
You create your own classes in Visual Basic with a class module. Class modules can contain several types of elements:
Properties. These elements are used to assign and retrieve values from the class.
Methods. These are public functions or subroutines that are defined in the class.
Events. Just as a control can raise events in the form that contains it, an object created from your class can also raise events in its containing object.
Class modules also contain two special events of their own, Initialize and Terminate. The Initialize event is triggered when a new instance of the class is created, and the Terminate event occurs when the object is destroyed.
Object definitions are created in a class module. A class module is like a standard code module in that it contains only variable declarations and procedure code. There is no user interface component of a class module. However, a class can take action using a form that is in the program, just like a normal code module. Class modules can be used in several ways, such as the following:
In a Visual Basic project, a class module provides a way to create multiple instances of objects anywhere in your program, without using global variables.
You can create ActiveX objects and compile them into a DLL or EXE that other programmers can use in their code. For example, you can put all of your business financial rules in a class and compile it as an ActiveX DLL. Other programmers can reference the DLL and use the financial rules in their applications.
You can build an Add-In to Visual Basic, to enhance the functions of the Visual Basic IDE.
Building Class Modules
The easiest way to learn is by doing, so let's create a simple class module. This sample class module will contain employee information. After you create the class module, you learn how to use the employee object in your program.

 
< previous page page_361 next page >